package com.example.a10928.weifriend.ui.home.menu;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.ViewDataBinding;
import android.os.Handler;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.View;

import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.example.a10928.weifriend.App;
import com.example.a10928.weifriend.R;
import com.example.a10928.weifriend.databinding.ActivityPaySelectBinding;
import com.example.a10928.weifriend.http.api.RowsWrapper;
import com.example.a10928.weifriend.http.api.VariableName;
import com.example.a10928.weifriend.ui.DatabindingBaseActivity;
import com.example.a10928.weifriend.ui.home.WebViewActivity;
import com.example.a10928.weifriend.util.L;
import com.example.a10928.weifriend.util.RxUtil;
import com.example.a10928.weifriend.view.TextRadioLayout;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.function.Consumer;

import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static com.example.a10928.weifriend.App.app;

public class PaySelectActvitiy extends DatabindingBaseActivity {

    private ActivityPaySelectBinding mBinding;
    private int payType = 1;
    private WerbenActivity.WerbenData werbenData;
    private int sourceType;
    public final static String SOURCE_PAYSELECTACTIVITY_TYPE = "sourcePaySelectActivity";
    public final static int SOURCE_WERBEN_ACTIVITY = 1001;
    public final static int SOURCE_VIP_ACTIVITY = 1002;
    public final static int SOURCE_TAKE_ACTIVITY = 1003;
    public final static String DATA_VIP_ACTIVITY = "werbenData";
    private int type;
    private String vipPrice;
    private int shopId;
    String two;
    String id;

    @Override
    protected void bindingInitData() {
        type = getIntent().getIntExtra(SOURCE_PAYSELECTACTIVITY_TYPE, -1);

        two=getIntent().getStringExtra(VariableName.TWOTYPE);

        switch (type) {
            default:
            case -1:
                return;
            case SOURCE_WERBEN_ACTIVITY:
                sourceType = SOURCE_WERBEN_ACTIVITY;
                werbenData = getIntent().getParcelableExtra("werbenData");
                break;
            case SOURCE_VIP_ACTIVITY:
                sourceType = SOURCE_VIP_ACTIVITY;
                vipPrice = getIntent().getStringExtra("werbenData");
                id= getIntent().getStringExtra(VariableName.TYPE);
                break;

            case SOURCE_TAKE_ACTIVITY:
                sourceType = SOURCE_TAKE_ACTIVITY;
                shopId = getIntent().getIntExtra(VariableName.DATA,0);
                break;
        }
    }

    @Override
    protected void bindingInitView(ViewDataBinding viewDataBinding) {
        // EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        mBinding = (ActivityPaySelectBinding) viewDataBinding;
        mBinding.setView(this);
        setTitleText(ThemeEnum.Back_Default, "选择支付");
        switch (type) {
            default:
            case -1:
                return;
            case SOURCE_WERBEN_ACTIVITY:
                mBinding.payNeedPrice.setText("需支付 " + (Double.parseDouble(werbenData.price) * Integer.parseInt(werbenData.number)) + " 元");
                break;
            case SOURCE_VIP_ACTIVITY:
                //getUpvipPrice();
                if(!TextUtils.isEmpty(vipPrice)){
                    mBinding.payNeedPrice.setText("需支付 "+Double.parseDouble(vipPrice));
                }
                break;
            case SOURCE_TAKE_ACTIVITY:
                //getUpvipPrice();

                    mBinding.payNeedPrice.setText("");

                break;

        }

    }

    @Override
    protected int bindingGetContentView() {
        return R.layout.activity_pay_select;
    }

    public void onViewClick(View v) {
        hideLayout(mBinding.payBalance, mBinding.payAlipay, mBinding.payUnionpay);
        switch (v.getId()) {
            case R.id.pay_balance:
                mBinding.payBalance.setChecked(true);
                payType = 1;
                break;
            case R.id.pay_alipay:
                mBinding.payAlipay.setChecked(true);
                payType = 2;
                break;

            case R.id.pay_unionpay:
                mBinding.payUnionpay.setChecked(true);
                payType = 4;
                break;

            case R.id.pay_bt_send:
                switch (sourceType) {
                    case SOURCE_WERBEN_ACTIVITY:
                        sendWerben();
                        break;
                    case SOURCE_VIP_ACTIVITY:
                        buyVip();
                        break;

                    case SOURCE_TAKE_ACTIVITY:
                        takeActivity();

                        break;
                }
                break;
        }
    }

    public void takeActivity(){
        app().getBpService().take_activity(app().getUser().getUserId(),app().getUser().getToken(),
                shopId,payType+"",two)
                .compose(RxUtil.io2mainLoad(this))
                .subscribe(
                        r->{
                            if(payType==1){
                                L.tLong(r.getMsg());
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        finish();
                                    }
                                },500);
                            }else {
                                selectPay(r);
                            }

                        },
                        e->{
                            RxUtil.errorException(e);
                        }
                );
    }

    @SuppressLint("CheckResult")
    private void buyVip() {

        if(payType==1){
            app().getBpService().buyVipTwo(app().getUser().getUserId(), payType, Double.parseDouble(vipPrice),id)
                    .compose(RxUtil.io2mainLoad(this))
                    .subscribe(
                            r -> {
                                L.tLong(r.getMessage());
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        finish();
                                    }
                                },500);
                            }, RxUtil::errorException
                    );
        }else{
            app().getBpService().buyVip(app().getUser().getUserId(), payType, Double.parseDouble(vipPrice),id)
                    .compose(RxUtil.io2mainLoad(this))
                    .subscribe(
                            r -> {

                                selectPay(r);
                            }, RxUtil::errorException
                    );
        }

    }

    @SuppressLint("CheckResult")
    private void getUpvipPrice() {

/*        app().getBpService().getUpvipPrice(app().getUser().getUserId())
                .compose(RxUtil.io2mainLoad(this))
                .subscribe(
                        r -> {
                            mBinding.payNeedPrice.setText("需支付 " + (99 - r.getData().getReduced_money()) + " 元(已随机减免 " + r.getData().getReduced_money() + " 元)");
                        }, RxUtil::errorException
                );*/
    }

    @SuppressLint("CheckResult")
    private void sendWerben() {
        if (werbenData == null) return;

        List<File> files = new ArrayList<>();
        for (LocalMedia localMedia : werbenData.imgList) {
            if (localMedia.isCompressed()) {
                files.add(new File(localMedia.getCompressPath()));
            } else {
                files.add(new File(localMedia.getPath()));
            }
        }

        List<MultipartBody.Part> bodyList = new ArrayList<>();
        for (File file : files) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            MultipartBody.Part body = MultipartBody.Part.createFormData("adver_img[]", file.getName(), requestBody);
            bodyList.add(body);
        }

        if(payType==1){
            app().getBpService().releraseAdverTwo(toRequestBody(werbenData.title), toRequestBody(werbenData.content), toRequestBody(werbenData.price), toRequestBody(werbenData.number), toRequestBody(payType + ""), toRequestBody(app().getUser().getUserId()), bodyList)
                    .compose(RxUtil.io2mainLoad(this))
                    .subscribe(
                            r -> {
                                L.tLong(r.getMsg());
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        finish();
                                    }
                                },500);
                            },
                            RxUtil::errorException
                    );
        }else{
            app().getBpService().releraseAdver(toRequestBody(werbenData.title), toRequestBody(werbenData.content), toRequestBody(werbenData.price), toRequestBody(werbenData.number), toRequestBody(payType + ""), toRequestBody(app().getUser().getUserId()), bodyList)
                    .compose(RxUtil.io2mainLoad(this))
                    .subscribe(
                            r -> {
                                selectPay(r);
                            },
                            RxUtil::errorException
                    );
        }

    }

    public RequestBody toRequestBody(String value) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), value);
        return requestBody;
    }

    public void hideLayout(TextRadioLayout... views) {
        for (TextRadioLayout v : views) {
            v.setChecked(false);
        }
    }

    private void selectPay(RowsWrapper<String> r) {
        switch (payType) {
            case 1: // 余额支付不用管
                L.tLong(r.getMsg());
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                },500);

                break;
            case 2: // 支付宝支付
                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        String orderInfo = r.getData();
                        if (orderInfo == null) return;
                        PayTask alipay = new PayTask(PaySelectActvitiy.this);
                        Map<String, String> result = alipay.payV2(orderInfo, true);

                    }
                };
                Thread payThread = new Thread(payRunnable);
                payThread.start();
//                                    io.reactivex.Observable<Object> objectObservable = io.reactivex.Observable.create(new ObservableOnSubscribe<Object>() {
//                                        @Override
//                                        public void subscribe(ObservableEmitter<Object> e) throws Exception {
//                                            String orderInfo = r.getData();
//                                            PayTask alipay = new PayTask(PaySelectActvitiy.this);
//                                            Map<String, String> result = alipay.payV2(orderInfo, true);
//                                        }
//                                    });
                break;

            case 4://银联支付

                Intent intent = new Intent(this, WebViewActivity.class);
                intent.putExtra(WebViewActivity.DADA_WEBVIEW_TITLE, WebViewActivity.SOURCE_UNIONPAY);
                intent.putExtra(VariableName.DATA, r.getData());
                startActivity(intent);
                break;
        }
      //  finish();
    }
}
